package com.py.credit.controller;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.py.credit.common.ServiceException;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.constant.OrgConstant;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.common.OptionalColumn;
import com.py.credit.entity.enums.OrgAccountTableFieldEnum;
import com.py.credit.service.OrgService;
import com.py.credit.service.XypjRemoteBaseService;
import com.py.credit.utils.ExcelUtil;
import com.py.credit.utils.MapCache;
import com.py.framework.core.common.Page;
import com.py.framework.core.helper.HttpServletHelper;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(tags = "account")
@RestController
@RequestMapping(value = "/account")
public class AccountController {

	private final static String FRONT_B_TABLE_ID = "bAccountTableList";

	@Autowired
	private OrgService orgService;

	@Autowired
	private XypjRemoteBaseService xypjRemoteBaseService;

	@ApiOperation(value = "获取机构账号列表", httpMethod = "POST", produces = "application/json")
	@RequestMapping(value = "/getBAccountList.json", method = RequestMethod.POST)
	public RestServiceResult<List<Map<String, Object>>> getFAccountList(
			@ApiParam(required = false, name = "conditions", value = "搜索条件") @RequestParam(required = false) String condition,
			Page page, HttpServletRequest request) {
		String[] configColumns = null;
		RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));

		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {

			SysUser userInfo = user.getData();

			if (null != userInfo) {

				configColumns = (String[]) MapCache.get(userInfo.getId() + "_" + FRONT_B_TABLE_ID);

			} else {

				ExceptionLogger.error("AccountController#getFAccountList", "未获取到当前用户信息！");
			}

		} else {

			ExceptionLogger.error("AccountController#getFAccountList", "未获取到当前用户信息！");
		}

		List<String> showColumns = (configColumns == null || configColumns.length == 0)
				? OrgAccountTableFieldEnum.getDefaultShowColumnEN() : Arrays.asList(configColumns);

		String[] additionalColumns = { "id", "orgId" };

		List<Map<String, Object>> orgList = orgService.getAccountListByConditionForPage(null, showColumns,
				additionalColumns, condition, page);
		return new RestServiceResult<List<Map<String, Object>>>(page.getTotalCount(), orgList);

	}

	@ApiOperation(value = "验证用户是否存在", httpMethod = "GET", produces = "application/json")
	@RequestMapping(value = "/validateAcccount.json", method = RequestMethod.GET)
	public RestServiceResult<Object> validateAcccount(
			@ApiParam(required = false, name = "account", value = "用户名") @RequestParam(required = true) String account) {

		if (orgService.isAccountExist(account)) {

			throw new ServiceException("账号已存在");

		}
		return new RestServiceResult<>();

	}

	@ApiOperation(value = "获取高级搜索条件", httpMethod = "GET", produces = "application/json")
	@RequestMapping(value = "/getAdvancedConditionColumns.json", method = RequestMethod.GET)
	public RestServiceResult<List<OptionalColumn>> getAdvancedConditionColumns() {

		return new RestServiceResult<List<OptionalColumn>>(OrgAccountTableFieldEnum.getAdvancedConditionColumns());

	}

	@ApiOperation(value = "获取表头列", httpMethod = "GET", produces = "application/json")
	@RequestMapping(value = "/getOptionalColums.json", method = RequestMethod.GET)
	public RestServiceResult<List<OptionalColumn>> getOptionalColums() {

		return new RestServiceResult<List<OptionalColumn>>(OrgAccountTableFieldEnum.getOptionalColumns());

	}

	@ApiOperation(value = "自定义展示列", httpMethod = "POST", produces = "application/json")
	@RequestMapping(value = "/addBColumns.json", method = RequestMethod.POST)
	public RestServiceResult<Object> addBColumns(
			@ApiParam(required = true, name = "columns", value = "展示列数组") @RequestParam(value = "columns", required = true) String[] columns,
			HttpServletRequest request) {
		RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));

		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {

			SysUser userInfo = user.getData();

			if (null != userInfo && userInfo.getId() != null) {

				MapCache.set(userInfo.getId() + "_" + FRONT_B_TABLE_ID, columns);
			} else {

				ExceptionLogger.error("AccountController#addBColumns", "未获取到当前用户信息！");
			}

		} else {

			ExceptionLogger.error("AccountController#addBColumns", "未获取到当前用户信息！");
		}

		return new RestServiceResult<Object>();

	}

	@ApiOperation(value = "导出列表", httpMethod = "GET")
	@RequestMapping("/bExport.json")
	public void bExport(
			@ApiParam(required = true, name = "condition", value = "搜索条件") @RequestParam(value = "condition", defaultValue = "", required = true) String condition,
			@ApiParam(required = true, name = "columnEN", value = "导出列") @RequestParam(value = "columnEN", required = true) String columnEN,
			HttpServletResponse response, HttpServletRequest request, Page page) throws IOException {

		page.setLimit(1000);

		List<String> columns = JSONArray.parseArray(columnEN, String.class);

		List<Map<String, Object>> data = orgService.getAccountListByConditionForPage(null, columns, null, condition,
				page);

		List<OptionalColumn> optionalColumns = OrgAccountTableFieldEnum.getOptionalColumns();

		ExcelUtil.downloadExcel(response, data, "账号列表", "账号列表", columns, optionalColumns);
	}

	@ApiOperation(value = "冻结账号", httpMethod = "POST", produces = "application/json")
	@RequestMapping(value = "/suspend.json", method = RequestMethod.POST)
	public RestServiceResult<Object> suspend(
			@ApiParam(required = true, name = "accountId", value = "账号编号") @RequestParam(value = "accountId", required = true) String accountId) {

		orgService.updateAccount(accountId, OrgConstant.ACCOUNT_STATUS_SUSPENDED);

		return new RestServiceResult<Object>();

	}

	@ApiOperation(value = "解冻账号", httpMethod = "POST", produces = "application/json")
	@RequestMapping(value = "/resume.json", method = RequestMethod.POST)
	public RestServiceResult<Object> resume(
			@ApiParam(required = true, name = "accountId", value = "账号编号") @RequestParam(value = "accountId", required = true) String accountId) {

		orgService.updateAccount(accountId, OrgConstant.ACCOUNT_STATUS_NORMAL);

		return new RestServiceResult<Object>();

	}

	@ApiOperation(value = "删除账号", httpMethod = "POST", produces = "application/json")
	@RequestMapping(value = "/delete.json", method = RequestMethod.POST)
	public RestServiceResult<Object> delete(
			@ApiParam(required = true, name = "accountId", value = "账号编号") @RequestParam(value = "accountId", required = true) String accountId) {

		// 检验是否是冻结的

		if (orgService.isSuspendedAccount(accountId)) {

			orgService.deleteAccount(accountId);

		} else {

			throw new ServiceException("只能删除冻结账号");

		}

		return new RestServiceResult<Object>();

	}

	@ApiOperation(value = "重置账号", httpMethod = "POST", produces = "application/json")
	@RequestMapping(value = "/reset.json", method = RequestMethod.POST)
	public RestServiceResult<Object> reset(
			@ApiParam(required = true, name = "accountId", value = "账号编号") @RequestParam(value = "accountId", required = true) String accountId,
			@ApiParam(required = true, name = "password", value = "密码") @RequestParam(value = "password", required = true) String password) {

		orgService.resetAccount(accountId, password);

		return new RestServiceResult<Object>();

	}

	@ApiOperation(value = "详情", httpMethod = "GET", produces = "application/json")
	@RequestMapping(value = "/detail.json", method = RequestMethod.GET)
	public RestServiceResult<Object> detail(
			@ApiParam(required = true, name = "orgId", value = "关联机构编号") @RequestParam(value = "orgId", required = true) String orgId) {

		Map<String, Object> result = orgService.getDetail(orgId);

		return new RestServiceResult<Object>(result);

	}

}
